package com.zrkizzy.seckill.controller.common;

import com.wf.captcha.ArithmeticCaptcha;
import com.zrkizzy.seckill.entity.User;
import com.zrkizzy.seckill.enums.HttpStatusEnum;
import com.zrkizzy.seckill.exception.GlobalException;
import com.zrkizzy.seckill.service.tool.IRedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static com.zrkizzy.seckill.constant.CommonConst.*;
import static com.zrkizzy.seckill.constant.RedisConst.KAPTCHA_PREFIX;
import static com.zrkizzy.seckill.constant.TimeConst.FIVE_MINUTE;

/**
 * 验证码控制器
 *
 * @author zhangrongkang
 * @since 2023/4/11
 */
@Slf4j
@Controller
@RequestMapping("/kaptcha")
public class KaptchaController {

    @Autowired
    private IRedisService redisService;

    /**
     * 秒杀接口验证码
     *
     * @param user 用户对象
     * @param goodsId 商品ID
     * @param response Response响应对象
     */
    @GetMapping("/seckill")
    public void verifyCode(User user, Long goodsId, HttpServletResponse response) {
        if (null == user || null == goodsId) {
            throw new GlobalException(HttpStatusEnum.REQUEST_ILLEGAL);
        }
        // 设置请求头输出为图片类型
        response.setContentType(IMAGE_JPG);
        // 设置请求头
        response.setHeader(PRAGMA, NO_CACHE);
        response.setHeader(CACHE_CONTROL, NO_CACHE);
        // 永不失效
        response.setDateHeader(EXPIRES, 0);
        // 生成算数类型验证码
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(140, 30, 3);
        // Redis存储验证码，过期时间为5分钟
        redisService.set(KAPTCHA_PREFIX + user.getId() + ":" + goodsId, captcha.text(), FIVE_MINUTE);
        try {
            // 输出验证码
            captcha.out(response.getOutputStream());
        } catch (IOException e) {
            log.error("验证码生成失败: {}", e.getMessage());
        }
    }
}
